<template>
  <div v-if="showLoader" class="auth-loader">
    <div class="loader-content">
      <div class="spinner">
        <div class="bounce1"></div>
        <div class="bounce2"></div>
        <div class="bounce3"></div>
      </div>
      <p class="loader-text">{{ loaderText }}</p>
      
      <!-- 错误状态 -->
      <div v-if="hasError" class="error-content">
        <el-alert
          :title="errorMessage"
          type="warning"
          :closable="false"
          show-icon
        />
        <div class="error-actions">
          <el-button type="primary" size="small" @click="retry">
            重试
          </el-button>
          <el-button size="small" @click="goToLogin">
            重新登录
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { useRouter } from 'vue-router'
import { globalAuth, useAuth } from '@/composables/useAuth'

const router = useRouter()
const { refreshAuth } = useAuth()

// 计算属性
const showLoader = computed(() => {
  return globalAuth.isInitializing.value
})

const hasError = computed(() => {
  return !!globalAuth.initializationError.value
})

const errorMessage = computed(() => {
  return globalAuth.initializationError.value || '认证失败'
})

const loaderText = computed(() => {
  if (hasError.value) {
    return '认证失败'
  }
  return '正在验证身份...'
})

// 方法
const retry = async () => {
  globalAuth.setError(null)
  await refreshAuth()
}

const goToLogin = () => {
  globalAuth.setError(null)
  router.push('/login')
}
</script>

<style lang="scss" scoped>
.auth-loader {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(4px);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
  
  .loader-content {
    text-align: center;
    max-width: 400px;
    padding: 40px;
    
    .spinner {
      width: 70px;
      margin: 0 auto 20px;
      text-align: center;
      
      > div {
        width: 18px;
        height: 18px;
        background-color: #409eff;
        border-radius: 100%;
        display: inline-block;
        animation: sk-bouncedelay 1.4s infinite ease-in-out both;
      }
      
      .bounce1 {
        animation-delay: -0.32s;
      }
      
      .bounce2 {
        animation-delay: -0.16s;
      }
    }
    
    .loader-text {
      margin: 0 0 20px 0;
      color: #606266;
      font-size: 14px;
    }
    
    .error-content {
      margin-top: 20px;
      
      .error-actions {
        margin-top: 15px;
        display: flex;
        gap: 10px;
        justify-content: center;
      }
    }
  }
}

@keyframes sk-bouncedelay {
  0%, 80%, 100% {
    transform: scale(0);
  } 40% {
    transform: scale(1.0);
  }
}

// 暗色主题适配
.dark .auth-loader {
  background: rgba(0, 0, 0, 0.95);
  
  .loader-content {
    .loader-text {
      color: #a3a6ad;
    }
  }
}
</style>
